<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path:'/goods'}">商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片区域-->
        <!--卡片区域-->
        <el-card>
            <!--消息提示-->
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" center show-icon :closable="false"></el-alert>

            <!-- 选择商品分类区域 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类: </span>
                    <!-- 商品分类的级联选择框 -->
                    <el-cascader
                            v-model="selectedCateKeys"
                            :options="cateList"
                            :props="selectOptions"
                            :show-all-levels="true"
                            clearable
                            @change="handleChange"></el-cascader>
                </el-col>
            </el-row>

            <!--tabs 标签页-->
            <el-tabs v-model="activeTabsName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="small" :disabled="this.isBtnDisable" @click="showAddDialog">添加参数</el-button>
                    <el-table border stripe :data="manyList" height="250" border style="width: 100%">
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 显示Tag文本框 -->
                                <el-tag :key="i"
                                        v-for="(item,i) in scope.row.attr_vals"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleClose(i,scope.row)">
                                    {{item}}
                                </el-tag>
                                <!-- 输入Tag文本框 -->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#" width="180"> </el-table-column>
                        <el-table-column prop="attr_name" label="参数名称" width="300"> </el-table-column>
                        <el-table-column prop="date" label="操作" >
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showManyDialog(scope.row)"></el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteData(scope.row.attr_id)"></el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="small" :disabled="this.isBtnDisable"@click="showAddDialog">添加属性</el-button>
                    <el-table border stripe :data="onlyList" height="250" border style="width: 100%">
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 显示Tag文本框 -->
                                <el-tag :key="i"
                                        v-for="(item,i) in scope.row.attr_vals"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleClose(i,scope.row)">
                                    {{item}}
                                </el-tag>
                                <!-- 输入Tag文本框 -->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#" width="180"> </el-table-column>
                        <el-table-column prop="attr_name" label="参数名称" width="300"> </el-table-column>
                        <el-table-column prop="date" label="操作" >
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showManyDialog(scope.row)"></el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteData(scope.row.attr_id)"></el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <!--动态参数 静态属性  添加对话框-->
            <el-dialog
                    :title="'添加'+this.getTitleText"
                    :visible.sync="addDialogVisible"
                    width="50%"
                    :before-close="addHandleClose">
                <el-form ref="addFormRef"
                         :rules="addFormRules"
                         :model="addForm"
                >
                    <el-form-item :label="this.getTitleText" prop="attr_name">
                        <el-input v-model="addForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addData">确 定</el-button>
              </span>
            </el-dialog>

            <!--动态参数 静态属性  编辑对话框-->
            <el-dialog
                    :title="'修改'+this.getTitleText"
                    :visible.sync="showDialogVisible"
                    width="50%"
                    :before-close="manyHandleClose">
                <el-form ref="editFormRef"
                        :rules="editFormRules"
                        :model="editForm"
                        >
                    <el-form-item :label="this.getTitleText" prop="attr_name">
                        <el-input v-model="editForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="showDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editData">确 定</el-button>
              </span>
            </el-dialog>

        </el-card>
    </div>
</template>

<script>
    export default {
        name: "Params",
        data(){
            return{
                editFormRules: {
                    attr_name: [
                        {required: true, message: '请输入参数', trigger: 'blur'},
                        {
                            min: 2,
                            max: 10,
                            message: '参数的长度在2～10个字',
                            trigger: 'blur'
                        }
                    ]
                },
                addFormRules:{
                    attr_name: [
                        {required: true, message: '请输入参数', trigger: 'blur'},
                        {
                            min: 2,
                            max: 10,
                            message: '参数的长度在2～10个字',
                            trigger: 'blur'
                        }
                    ]
                },
                // 商品 列表
                cateList:[],
                // 商品分类 级联双向数据绑定
                selectedCateKeys:[],
                // 级联选择框的配置对象
                selectOptions:{
                    // 次级 菜单展开的方式
                    expandTrigger:'hover',
                    value: 'cat_id',
                    label: 'cat_name',
                    children:'children'
                },
                activeTabsName:'many',
                // 动态数据 列表
                manyList:[],
                // 动态参数 编辑对话框 对象
                editForm:{
                },
                // 静态数据 列表
                onlyList:[],
                //动态参数  编辑对话框
                showDialogVisible:false,
                // 动态参数 静态 添加对话框
                addDialogVisible:false,
                // 添加 动态 静态 参数 对象
                addForm:{},
                // 动态参数  列表
                dynamicTags:[],
                inputVisible:'',
                inputValue:''
            }
        },
        created() {
            this.getCateList()
        },
        computed:{
            // 计算  分类ID
            getCateId(){
                if (this.selectedCateKeys.length === 3){
                    return this.selectedCateKeys[2]
                }
                return null
            },
            // 按钮  是否警用
            isBtnDisable(){
                //console.log("选中字典："+this.selectedCateKeys.length);
                if (this.selectedCateKeys.length === 3){
                    return false
                }
                return true
            },
            getTitleText () {
                if (this.activeTabsName === 'many') {
                    return '动态参数'
                }
                return '静态属性'
            }
        },
        methods:{
            // 级联触发 事件
            handleChange(){
                //console.log('级联触发的事件');
                this.getParamsData()
            },
            // 获取 商品 分类
            async getCateList(){
                await this.$http.get('categories').then(res=>{
                    if (res.data.meta.status !== 200){
                        return this.$message.error('获取参数列表失败！')
                    }
                    this.cateList = res.data.data
                }).catch(err=>{
                    console.log(err);
                })



            },
            handleClick(){
                //console.log('切换tab标签'+this.activeTabsName);
                this.getParamsData()
            },
            // 获取参数的列表数据
            async getParamsData(){
                // 根据所选分类的Id,和当前面板的参数, 获取对应的参数
                await this.$http.get(`categories/${this.getCateId}/attributes`,{
                    params: { sel: this.activeTabsName }
                }).then(res=>{
                    if (res.data.meta.status !== 200){
                        this.$message.error('获取动态参数列表失败!')
                    }
                    res.data.data.forEach(item => {
                        //   通过三元表达式判断attr_vals是否为空
                        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []

                        // 控制文本框的显示与隐藏
                        item.inputVisible = false
                        // 文本框的输入值
                        item.inputValue = ''
                    })
                   if (this.activeTabsName === 'many'){
                       this.manyList = res.data.data
                   }else {
                       this.onlyList = res.data.data
                   }
                    console.log(res.data.data);
                }).catch(err=>{

                })

            },
            //动态参数 静态属性 -> 编辑对话框
            async showManyDialog(row){
                this.showDialogVisible = true
                this.editForm = row
            },
            // 动态参数 静态属性  ->
            manyHandleClose(){
                this.showDialogVisible = false
                this.$refs.editFormRef.resetFields()
            },
            // 修改动态参数   静态属性
             editData(){
                 this.$refs.editFormRef.validate(async valid => {
                 if (!valid) return
                    await this.$http.put(
                        `categories/${this.getCateId}/attributes/${this.editForm.attr_id}`,
                        {
                            attr_name: this.editForm.attr_name,
                            attr_sel: this.activeTabsName
                        }
                    ).then(res=>{
                        if (res.data.meta.status !== 200) {
                            return this.$message.error('修改参数失败！')
                        }
                        this.$message.success('修改参数成功！')
                        // 刷新 列表
                        this.getParamsData()
                    }).catch(err=>{

                    })
                })
                this.showDialogVisible = false
            },
            // 静态 动态 属性
            addHandleClose(){
                //console.log('对话框关闭');
                this.addDialogVisible = false
                this.$refs.addFormRef.resetFields()
            },
            showAddDialog(){
                this.addDialogVisible = true
            },
            // 添加 动态 静态 参数
            addData(){
                this.$refs.addFormRef.validate(async valid =>{
                    if (!valid) return
                    await this.$http.post(`categories/${this.getCateId}/attributes`,{
                        attr_name: this.addForm.attr_name,
                        attr_sel: this.activeTabsName
                    }).then(res=>{
                        if (res.data.meta.status !== 201){
                            this.$message.error('添加失败!')
                        }
                        this.$message.success('添加成功!')
                        this.addDialogVisible = false
                        this.getParamsData()
                    }).catch(err=>{
                        console.log(err);
                    })
                })
            },
             deleteData(attrId){
              this.$confirm(
                    '是否要删除此数据?',
                    '提示',
                    {
                        confirmButtonText:'删除',
                        cancelButtonText:'取消'
                    }
                ).then(res=>{
                    this.$http.delete(
                        `categories/${this.getCateId}/attributes/${attrId}`
                    ).then(res=>{
                        if (res.data.meta.status !== 200){
                            this.$message.error('删除参数失败!')
                        }
                        this.$message.success('删除数据成功!')
                        this.getParamsData()
                    }).catch(err=>{
                        console.log(err);
                    })
                }).catch(err=>{
                    this.$message.error('已取消删除操作!')
                })
            },
            //点击展开 动态参数 列表
            handleClose(i,row){
                row.attr_vals.splice(i,1)
                this.saveAttrVals(row)
            },
            //// 文本框失去焦点,或者按下Enter触发
            handleInputConfirm(row){
                console.log('失去焦点触发'+row);
                // 输入的内容为空时，清空
                if (row.inputValue.trim().length === 0) {
                    row.inputValue = ''
                    row.inputVisible = false
                    return
                }
                row.attr_vals.push(row.inputValue.trim())
                row.inputValue = ''
                row.inputVisible = false
                // 提交数据库，保存修改
                this.saveAttrVals(row)
            },
            // 点击按钮显示输入框
            showInput(row){
                row.inputVisible = true
                //   让输入框自动获取焦点
                // $nextTick方法的作用：当页面元素被重新渲染之后，才会至指定回调函数中的代码
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus()
                })
            },
            // 将对attr_vals（Tag） 的操作 保存到数据库
            async saveAttrVals(row){
                await this.$http.put(`categories/${this.getCateId}/attributes/${row.attr_id}`,{
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                }).then(res=>{
                    if (res.data.meta.status !== 200) {
                        return this.$message.error('修改参数项失败！')
                    }
                    this.$message.success('修改参数项成功！')
                })
            }
        }
    }
</script>

<style scoped>
    .el-tag + .el-tag {
        margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>